<template>
  <div class="teacher-container">
    <div class="content-wrapper">
      <!-- 左侧：提交课程发布申请 -->
      <div class="submit-form">
        <h1>提交课程发布申请</h1>
        <form @submit.prevent="requestPublishCourse">
          <label for="courseSelect">选择课程:</label>
          <select id="courseSelect" v-model="selectedCourseId" required>
            <option disabled value="">请选择课程</option>
            <option v-for="course in availableCourses" :key="course.cno" :value="course.cno">
              {{ course.cname }}
            </option>
          </select>

          <label for="residueInput">修改名额:</label>
          <input id="residueInput" type="number" v-model.number="newResidue" min="0" required />

          <button type="submit">提交申请</button>
        </form>
      </div>

      <!-- 右侧：已提交的发布申请 -->
      <div class="submitted-requests">
        <h2>已提交的发布申请</h2>
        <table v-if="submittedRequests.length > 0">
          <thead>
          <tr>
            <th>课程编号</th>
            <th>课程名称</th>
            <th>名额</th>
            <th>状态</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(request, index) in submittedRequests" :key="index">
            <td>{{ request.cno }}</td>
            <td>{{ request.cname }}</td>
            <td>{{ request.residue }}</td>
            <td>{{ getStatusText(request.isopen) }}</td>
          </tr>
          </tbody>
        </table>
        <p v-else>暂无已提交的发布申请。</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';

const selectedCourseId = ref('');
const newResidue = ref(0);
const availableCourses = ref([]);
const submittedRequests = ref([]);

// 使用 Vue Router 获取当前路由信息
const route = useRoute();
const getLoggedInTeacherTno = () => route.query.id;
const teacherTno = ref(getLoggedInTeacherTno());

// 获取可用课程列表
const fetchAvailableCourses = async () => {
  try {
    const response = await axios.get('http://localhost:8080/teacher/courses/available');
    availableCourses.value = response.data;
  } catch (error) {
    console.error('获取课程失败:', error);
  }
};

// 提交课程发布申请
const requestPublishCourse = async () => {
  if (!selectedCourseId.value || isNaN(newResidue.value) || newResidue.value <= 0) {
    alert('请选择课程并填写有效的名额。');
    return;
  }

  const selectedCourse = availableCourses.value.find(course => course.cno === selectedCourseId.value);

  if (!selectedCourse) {
    alert('所选课程未找到，请重新选择。');
    return;
  }

  try {
    // 提交请求给后端，包含新的名额和apply=1（表示申请）
    await axios.put('http://localhost:8080/teacher/request', null, {
      params: {
        tno: teacherTno.value,
        residue: newResidue.value,
        apply: 1, // 申请发布
        cname: selectedCourse.cname
      }
    });

    // 更新本地状态
    submittedRequests.value.push({
      cname: selectedCourse.cname,
      residue: newResidue.value,
      isopen: 0, // 初始状态为待审查
      cno: selectedCourse.cno
    });

    alert('申请已提交');
    selectedCourseId.value = ''; // 清空选择框
    newResidue.value = 0; // 清空名额输入框
  } catch (error) {
    console.error('提交申请失败:', error);
    alert('提交申请失败，请稍后再试');
  }
};

// 获取已提交的发布申请列表
const fetchSubmittedRequests = async () => {
  try {
    const response = await axios.get('http://localhost:8080/teacher/pending', {
      params: { tno: teacherTno.value }
    });
    // 使用服务器响应的数据填充 submittedRequests
    submittedRequests.value = response.data;
  } catch (error) {
    console.error('获取已提交的申请失败:', error);
  }
};

// 根据isopen值返回状态文本
const getStatusText = (isopen) => {
  switch (isopen) {
    case 0:
      return '待审查';
    case 1:
      return '已批准';
    case 3:
      return '已拒绝';
    default:
      return '未知状态';
  }
};

// 在组件挂载时启动定时任务
onMounted(() => {
  // 首次加载时获取数据
  fetchAvailableCourses();
  fetchSubmittedRequests(); // 初始化时加载已提交的请求状态
});
</script>

<style scoped>
/* 样式部分保持不变 */
.teacher-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-wrapper {
  display: flex;
  width: 100%;
  max-width: 1200px; /* 控制最大宽度 */
  justify-content: space-between;
  gap: 20px; /* 两栏之间的间距 */
}

.submit-form, .submitted-requests {
  flex: 1;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.submit-form form {
  display: flex;
  flex-direction: column;
  width: 100%;
}

label {
  margin-top: 10px;
}

input, select, button {
  margin-top: 5px;
  padding: 8px;
  width: 100%;
  box-sizing: border-box;
}

table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

tr:hover {
  background-color: #f1f1f1;
}

button {
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:disabled {
  background-color: gray;
}
</style>